package service

import (
	"context"
	"e-commerce/services/inventory-service/internal/mq"
	"e-commerce/services/inventory-service/internal/repository"

	"github.com/streadway/amqp"
)

type InventoryService struct {
	repo *repository.InventoryRepository
	mq   *mq.RabbitMQ
}

func NewInventoryService(configPath string) *InventoryService {
	repo := repository.NewMySQLRepository(configPath)
	mq := mq.NewRabbitMQ(configPath)
	return &InventoryService{repo: repo, mq: mq}
}

func (s *InventoryService) ReserveStock(productID string, quantity int32) error {
	return s.repo.ReserveStock(productID, quantity)
}

func (s *InventoryService) ReleaseStock(ctx context.Context, orderID int64) error {
	productID, quantity, err := s.mq.GetOrderData(ctx, orderID)
	if err != nil {
		return err
	}
	return s.repo.ReleaseStock(productID, quantity)
}

func (s *InventoryService) QueryStock(productID string) (int32, error) {
	return s.repo.QueryStock(productID)
}

func (s *InventoryService) Consume(
	queue string,
	handler func(msg amqp.Delivery, inventoryRepository *repository.InventoryRepository, mq *mq.RabbitMQ) error,
) error {
	return s.mq.Consume(queue, handler, s.repo)
}

func (s *InventoryService) ReservedConsume() error {
	return s.Consume("inventory.reserve", mq.HandleReservedMessage)
}

func (s *InventoryService) RollbackConsume() error {
	return s.Consume("inventory.rollback", mq.HandleRollbackMessage)
}

func (s *InventoryService) CreateStock(productID string, quantity int32) error {
	return s.repo.CreateStock(productID, quantity)
}

func (s *InventoryService) NewOrderQueue() error {
	return s.mq.NewOrderQueue()
}
